Search a 2D matrix¶
Time: O(LogM+LogN); Space: O(1); medium
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix =
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
],
target = 3
Output: True
Example 2:
Input: matrix =
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
],
target = 13
Output: False
1. Binary Search [O(LogM+LogN), O(1)]¶
[1]:
class Solution1(object):
"""
Time: O(LogM+LogN)
Space: O(1)
"""
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n
while left < right:
mid = left + (right - left) // 2
if matrix[mid // n][mid % n] >= target:
right = mid
else:
left = mid + 1
return left < m * n and matrix[left // n][left % n] == target
[2]:
s = Solution1()
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
assert s.searchMatrix(matrix, target) == True
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
assert s.searchMatrix(matrix, target) == False